package com.transpeed.payservice.log;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Log {
	private static String logFilePath;
	private static FileWriter logWriter = null;
	private static boolean printLogWhenLog = true;

	// 关键信息日志记录
	public static void Write(String message, String LogFileName) {
		InitLogger(LogFileName);
		Date logfileDate = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
		StackTraceElement callingClassName = new Exception().getStackTrace()[1];
		synchronized (logWriter) {
			String log = String.format("[%s]:[%s]:%s\n", callingClassName,
					dateFormat.format(logfileDate), message);
			if (printLogWhenLog) {
				System.out.printf("[log]:%s", log);
			}
			try {
				logWriter.write(log);
				logWriter.flush();
			} catch (IOException e) {
				System.err.println("Write log to file %s error.");
				e.printStackTrace();
			}
		}
	}

	private static boolean InitLogger(String LogFileName) {
		Date logfileDate = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("HH");
		SimpleDateFormat dateFormatday = new SimpleDateFormat("yyyy-MM-dd");

		String logDirectoryPath = LogUtils.getDirectory(LogFileName)
				+ java.io.File.separatorChar
				+ dateFormatday.format(logfileDate);

		LogUtils.CreateLogFile(logDirectoryPath);

		logFilePath = logDirectoryPath + java.io.File.separatorChar
				+ LogFileName + "~" + dateFormat.format(logfileDate) + ".log";
		// System.out.println(logFilePath);
		try {
			logWriter = new FileWriter(logFilePath, true);
		} catch (IOException e) {

			System.err
					.println("Initilization fail! Unable to create log file!");
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
